package com.test.framework.beans.factory.xml;

import com.test.framework.beans.BeanDefinition;
import com.test.framework.beans.MutablePropertyValues;
import com.test.framework.beans.PropertyValue;
import com.test.framework.beans.factory.support.BeanDefinitionReader;
import com.test.framework.beans.factory.support.BeanDefinitionRegistry;
import com.test.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ClassName: XmlBeanDefinitionReader
 * @description: 针对xml配置文件进行解析的类
 * @author: Mr du
 * @create: 2024-04-09 21:25
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }
    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configLocation);
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element rootElement = document.getRootElement();
        this.parseBean(rootElement);
    }

    /**
     * 解析bean标签
     * @param rootElement
     */
    private void parseBean(Element rootElement){
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String className = element.attributeValue("class");
            //定义Bean标签存储器
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            List<Element> list = element.elements("property");
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            //定义property标签存储器
            for (Element propertyElement : list) {
                String name = propertyElement.attributeValue("name");
                String ref = propertyElement.attributeValue("ref");
                String value = propertyElement.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name,ref,value);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }
            beanDefinition.setPropertyValues(mutablePropertyValues);
            //注册容器
            registry.registerBeanDefinition(id,beanDefinition);
        }
    }
}
